package sv.gob.mh.dgii.ssc.security.controller;

import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.ldap.search.LdapUserSearch;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class LoginController {
    
    @Autowired
    private LdapUserSearch filterUserSearch;

    @RequestMapping(value = "/login")
    public String login() {
        
        return "security/login";
    }

    @RequestMapping(value = "/failLogin", method = RequestMethod.GET)
    public String failLogin(HttpServletRequest request) {
        request.setAttribute("error", "true");
        return "security/login";
    }
    
    
    @RequestMapping(value = "/logon", method = RequestMethod.POST)
    public String processLogin(HttpServletRequest request) {
        
        String username = (String) request.getParameter(
				"j_username");
        
        request.getSession().setAttribute("h0x_password",
				(String) request.getParameter("j_password"));
	request.getSession().setAttribute("h0x_username", username);
        
        DirContextOperations user = null;
            try {
		user = filterUserSearch.searchForUser(username);
		System.out.println("Ingreso correctamente " + user.getDn());
                return "redirect:/loginaction";

            } catch (UsernameNotFoundException e) {				
		 e.printStackTrace();
            }
        
        System.out.println("PROCESANDO LOGIN");
        return "security/login";
    }
}